package com.sws.controllers;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sws.models.RoleForUser;
import com.sws.models.RoleForUserDao;
import com.sws.models.User;
import com.sws.models.UserDao;

@Controller
public class loginController {
	
	private UserDao userDao;
	private RoleForUserDao roleForUserDao;
	
	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	@Autowired
	public void setRoleForUserDao(RoleForUserDao roleForUserDao) {
		this.roleForUserDao = roleForUserDao;
	}

	@RequestMapping({ "/login" })
	public String showLoginPage(Map<String, Object> model, 
			HttpServletRequest request, 
			HttpServletResponse response) {
		
		return "login";
	}
	
	@RequestMapping({ "/register" })
	public String showRegisterPage(Map<String, Object> model, 
			HttpServletRequest request, 
			HttpServletResponse response) {
		
		model.put("user", new User());
		
		return "register";
	}
	
	@RequestMapping(value="/register", method=RequestMethod.POST)
	public String addSpitterFromForm(@Valid User user, BindingResult bindingResult)
	{
		if(bindingResult.hasErrors()) 
		{
			return "register";
		}
		userDao.saveUser(user);
		RoleForUser role = new RoleForUser();
		role.setUser(user);
		role.setName("ROLE_SWSUSER");
		roleForUserDao.saveRole(role);
		return "redirect:/login?register=success";
	}

		
	
}
